package com.itheima.mm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mm.context.BaseContext;
import com.itheima.mm.dto.IndustryDTO;
import com.itheima.mm.entity.IndustryPageQueryParams;
import com.itheima.mm.entity.PageResult;
import com.itheima.mm.entity.QueryPageBean;
import com.itheima.mm.mapper.IndustryMapper;
import com.itheima.mm.mapper.UserMapper;
import com.itheima.mm.pojo.Industry;
import com.itheima.mm.pojo.User;
import com.itheima.mm.service.IndustryService;
import com.itheima.mm.utils.DateUtils;
import com.itheima.mm.vo.IndustryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description IndustryServiceImpl
 * @Author xiao
 * @Date 2024-06-26
 */

@Service
public class IndustryServiceImpl implements IndustryService {

    @Autowired
    private IndustryMapper industryMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public List<IndustryVO> findListAll() {
        List<Industry> industryList = industryMapper.selectListAll();

        List<IndustryVO> industryVOList = industryList.stream().map(industry->{
            IndustryVO industryVO = new IndustryVO();
            BeanUtils.copyProperties(industry,industryVO);
            return industryVO;
        }).collect(Collectors.toList());

        return industryVOList;
    }

    @Override
    public PageResult<IndustryVO> findListByPage(QueryPageBean<IndustryPageQueryParams> queryPageBean) {
            Integer currentPage = queryPageBean.getCurrentPage();
            Integer pageSize = queryPageBean.getPageSize();
            IndustryPageQueryParams queryParams  = queryPageBean.getQueryParams();
            //queryPageBean 主对象（包括第几页，这一页有几张，以及筛选条件）
            //queryParams  子对象  （筛选条件信息）

            PageHelper.startPage(currentPage,pageSize);
            Page<IndustryVO> page = industryMapper.findByConditon(queryParams);
            System.out.println("page data:" + page.toString());

            Long total = page.getTotal();
            List<IndustryVO> industryVOList = page.getResult();

            PageResult<IndustryVO> pageResult = new PageResult<>(total,industryVOList);
            System.out.println("pageResultData:" + pageResult.toString());
            return pageResult;
    }

    @Override
    public void add(IndustryDTO industryDTO) {
        Industry industry = new Industry();

        BeanUtils.copyProperties(industryDTO,industry);
        industry.setCreateDate(DateUtils.parseDate2String(new Date()));
        //查一手用户名
        User user = userMapper.findById(BaseContext.getCurrentId());
        industry.setCreater(user.getUsername());

        industryMapper.add(industry);
    }

    @Override
    public void delete(Integer id) {
        industryMapper.delete(id);
    }
}
